# -*- coding: utf-8 -*-

import os
import inspect
import datetime
import logging
from logging.handlers import RotatingFileHandler
import time

#-------------project bag---------------
import config


# CurrentPath = os.getcwd()
CurrentPath=os.path.dirname(os.path.dirname(__file__))

LOG = []


def log_init():
    log_path = os.path.join(CurrentPath, "log")
    os.mkdir(log_path) if not os.path.isdir(log_path) else None
    log_name = "%s\\log\\server.log" % CurrentPath
    logging.basicConfig(level=logging.INFO)
    Rthandler = RotatingFileHandler(log_name, maxBytes=10 * 1024 * 1024, backupCount=10)
    Rthandler.setLevel(logging.INFO)
    logging_format = logging.Formatter(
        '[%(asctime)s] %(filename)s [func:%(funcName)s] [line:%(lineno)d] %(levelname)s: %(message)s')
    Rthandler.setFormatter(logging_format)
    logging.getLogger('').addHandler(Rthandler)
    return logging
logger = log_init()


def wlog(content=0):
    global LOG
    content = str(content)
    cf = inspect.stack()
    ct = datetime.datetime.now()
    # print cf
    current_file = str(cf[1][1])
    current_fun = str(cf[1][3])
    c_year = str(ct.year)
    c_month = str(ct.month)
    c_day = str(ct.day)
    c_hour = str(ct.hour)
    c_min = str(ct.minute)
    c_sec = str(ct.second)
    s = '[%s-%s-%s %s:%s:%s]["%s","%s"]%s' % (c_year,c_month,c_day,c_hour,c_min,c_sec,current_file,current_fun,content)
    LOG.append(s)
    if len(LOG) > int(config.getConfig('logging','num')):
        record_log(LOG)
        LOG = []


def record_log(log):
    '''
    如果没有这个log文件，就新建
    如果log文件太大，就新建
    '''
    global CurrentPath
    size = int(config.getConfig('logging','size'))    #Mega
    path = CurrentPath+'/log/'
    log_path=path +'log.txt'
    if not os.path.exists(path):
        os.makedirs(path)
    if os.path.exists('%s' % (log_path)):
        filesize = os.path.getsize(log_path)/1024/1024
        if filesize > size:
            num = 1
            while True:
                copy_log_path = path+'log(%s).txt' % (str(num))
                if os.path.exists(copy_log_path):
                    num += 1
                    continue
                break
            os.rename(log_path, copy_log_path)

        else:
            f = open('%s' % (log_path), 'a')

    if not os.path.exists('%s' % (log_path)):
        f = open('%s' % (log_path),'w')

    if type(log) == list:
        for content in log:
            f.write(str(content)+'\n')
    else:
        content = str(log)
        f.write(content+'\n')
    f.close()
    print 'succeed to record log'
